package com.qiumo.gmtool.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiumo.gmtool.common.RetResult;
import com.qiumo.gmtool.config.GenshinConfig;
import com.qiumo.gmtool.entity.UserEntity;
import com.qiumo.gmtool.entity.user.UserRegisterDto;
import com.qiumo.gmtool.mail.MailParams;
import com.qiumo.gmtool.mail.MailUtil;
import com.qiumo.gmtool.service.UserService;
import java.util.Random;
import javax.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 通用
 */
@RestController
@RequestMapping("/common")
@Slf4j
@RequiredArgsConstructor
public class CommonController {

    private final UserService userService;

    @Resource
    MailUtil mailUtil;

    /**
     * 验证码长度
     */
    @Value("${genshin.codelength}")
    private Integer codeLength;

    /**
     * 验证码有效时间
     */
    @Value("${genshin.expiretime}")
    private Integer expireTime;

    @Value("${genshin.title}")
    public String title;

    /**
     * 注册获取验证码
     */
    @GetMapping("/getRegisterCode/{uid}")
    public RetResult getRegisterCode(@PathVariable String uid) {
        UserEntity user = userService.getOne(new QueryWrapper<UserEntity>().eq("uid", uid));
        if (ObjectUtil.isNotEmpty(user)) {
            return RetResult.err("UID已注册，请直接登录");
        }
        MailParams params = new MailParams();
        params.setUid(uid);
        //标题
        params.setTitle("欢迎注册" + title + "GM工具");
        //生成验证码，放入缓存
        String captcha = CAPTCHA(codeLength);
        GenshinConfig.codeCache.put(uid + "reg", captcha);
        //内容
        params.setContent(
            "您的注册验证码是：" + captcha + ",验证码" + expireTime + "分钟内有效,请勿将验证码泄露给别人，已防数据丢失。");
        log.info("UID注册:{} 验证码{}", uid, captcha);
        return mailUtil.sendMail(params);
    }

    /**
     * 登录获取验证码
     */
    @GetMapping("/getLoginCode/{uid}")
    public RetResult getLoginCode(@PathVariable String uid) {
        UserEntity user = userService.getOne(new QueryWrapper<UserEntity>().eq("uid", uid));
        if (ObjectUtil.isEmpty(user)) {
            return RetResult.err("UID未注册，请先注册账号");
        }
        //管理员不发送邮件
        if (user.getRole().equals("SUPERADMIN") || user.getRole().equals("ADMIN")) {
            log.info("超管登录:{} 验证码{}", uid, "无");
            return RetResult.succMsg("ok");
        }
        MailParams params = new MailParams();
        params.setUid(uid);
        //标题
        params.setTitle("欢迎登录" + title + "GM工具");
        //生成验证码，放入缓存
        String captcha = CAPTCHA(codeLength);
        GenshinConfig.codeCache.put(uid + "login", captcha);
        //内容
        params.setContent(
            "您的登录验证码是：" + captcha + ",验证码" + expireTime + "分钟内有效,请勿将验证码泄露给别人，已防数据丢失。");
        log.info("UID登录:{} 验证码{}", uid, captcha);
        return mailUtil.sendMail(params);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public RetResult register(@RequestBody UserRegisterDto dto) {
        if (ObjectUtil.isEmpty(dto.getUid())) {
            return RetResult.err("UID不能为空");
        }
        if (ObjectUtil.isEmpty(dto.getCode())) {
            return RetResult.err("验证码不能为空");
        }
        if (ObjectUtil.isEmpty(dto.getQqNum())) {
            return RetResult.err("QQ号码不能为空");
        }
        UserEntity user = userService.getOne(new QueryWrapper<UserEntity>().eq("uid", dto.getUid()));
        if (ObjectUtil.isNotEmpty(user)) {
            return RetResult.err("UID已注册，请直接登录");
        }
        // 验证验证码
        if (ObjectUtil.isEmpty(GenshinConfig.codeCache.get(dto.getUid() + "reg")) ||
            !GenshinConfig.codeCache.get(dto.getUid() + "reg").equals(dto.getCode())) {
            return RetResult.err("验证码错误，请重新输入");
        }
        //验证码成功 主动清除验证码
        GenshinConfig.codeCache.remove(dto.getUid() + "reg");
        //新增用户到数据库
        UserEntity userEntity = new UserEntity();
        userEntity.setUid(dto.getUid());
        userEntity.setRole("USER");
        userEntity.setQqNum(dto.getQqNum());
        userEntity.setRemark("验证码注册用户");
        userService.save(userEntity);
        return RetResult.succMsg("注册成功");
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public RetResult login(@RequestBody UserRegisterDto dto) {
        if (ObjectUtil.isEmpty(dto.getUid())) {
            return RetResult.err("UID不能为空");
        }
        if (ObjectUtil.isEmpty(dto.getCode())) {
            return RetResult.err("验证码不能为空");
        }
        UserEntity user = userService.getOne(new QueryWrapper<UserEntity>().eq("uid", dto.getUid()));
        if (ObjectUtil.isEmpty(user)) {
            return RetResult.err("UID未注册，请先注册账号");
        }
        // 管理员密码验证
        if (user.getRole().equals("SUPERADMIN") || user.getRole().equals("ADMIN")) {
            log.info("超管登录:{} 验证码{}", user.getUid(), "无");
            if (!user.getPassword().equals(dto.getCode())) {
                return RetResult.err("验证码错误，请重新输入");
            }
        } else {
            // 玩家验证验证码
            if (ObjectUtil.isEmpty(GenshinConfig.codeCache.get(dto.getUid() + "login")) ||
                !GenshinConfig.codeCache.get(dto.getUid() + "login").equals(dto.getCode())) {
                return RetResult.err("验证码错误，请重新输入");
            } else {
                //验证码成功 主动清除验证码
                GenshinConfig.codeCache.remove(dto.getUid() + "login");
            }
        }
        StpUtil.login(dto.getUid());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return RetResult.succ("登录成功", tokenInfo);
    }

    /**
     * 获取在线人数
     */
    @GetMapping("/getOnLine")
    public RetResult getOnLine() {
        return mailUtil.getOnline();
    }

    /**
     * 获取验证码
     *
     * @param n 长度
     */
    private static String CAPTCHA(int n) {
        Random r = new Random();
        String code = " ";//分配一个空字符内存
        for (int i = 0; i < n; i++) {
//            int type = r.nextInt(3);
            int type = 2;// 改成纯数字
            switch (type) {
                case 0://大写字母
                    char c0 = (char) (r.nextInt(26) + 65);//ASII中大写字母的范围
                    code += c0;
                    break;
                case 1://小写字母
                    char c1 = (char) (r.nextInt(26) + 97);//ASII中小写字母的范围
                    code += c1;
                    break;
                case 2://数字
                    int m = r.nextInt(10);//生成0~9的随机数
                    code += m;
                    break;

            }
        }
        return code.trim().toLowerCase();
    }

}
